//
//  SongListCell.swift
//  TimMusic
//
//  Created by nkl on 2024/10/10.
//

import Foundation
import TSVideoKit
import UIKit

class SongListCell: UITableViewCell {
    var likeButtonAction: (TSVideo) -> Void = { _ in }

    lazy var iconView: UIImageView = .simpleImage(imageName: "")
    lazy var nameLabel: UILabel = .simpleLabel(text: "--", font: .systemFont16, color: .white)
    lazy var detailLabel: UILabel = .simpleLabel(text: "--", font: .systemFont14, color: .white.withAlphaComponent(0.4))
    lazy var likeButton: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "ic_fav_light"), for: .selected)
        btn.setImage(UIImage(named: "ic_fav_normal"), for: .normal)
        btn.addTarget(self, action: #selector(likeButtonClickEvent), for: .touchUpInside)
        return btn
    }()

    fileprivate var video: TSVideo?

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        addChildren()
        makeConstraints()
    }

    func bindData(video: TSVideo) {
        nameLabel.text = video.title
        detailLabel.text = video.artist
        if let artData = video.artwork,
           let img = UIImage(data: artData) {
            iconView.image = img
        }
        self.likeButton.isSelected = video.isFavorite
        self.video = video
    }

    @objc func likeButtonClickEvent() {
        guard let video = video else {
            return
        }
        likeButtonAction(video)
    }

    func addChildren() {
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        iconView.layer.cornerRadius = 8
        iconView.layer.masksToBounds = true
        contentView.addSubview(iconView)
        contentView.addSubview(nameLabel)
        contentView.addSubview(detailLabel)
        contentView.addSubview(likeButton)
    }

    func makeConstraints() {
        iconView.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(20)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(44)
        }

        nameLabel.snp.makeConstraints { make in
            make.leading.equalTo(iconView.snp.trailing).offset(14)
            make.trailing.equalTo(likeButton.snp.leading).offset(-12)
            make.top.equalTo(iconView)
        }

        detailLabel.snp.makeConstraints { make in
            make.leading.equalTo(iconView.snp.trailing).offset(14)
            make.trailing.equalTo(likeButton.snp.leading).offset(-12)
            make.bottom.equalTo(iconView)
        }

        likeButton.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-20)
            make.width.height.equalTo(40)
            make.centerY.equalToSuperview()
        }
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
